#include"Heap.h"
void HPInit(HP* php) {
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}
void HPDestroy(HP* php) {
	assert(php);
	if (php->arr) {
		free(php->arr);
		php->arr = NULL;
	}
	php->capacity = php->size = 0;
}
void swap(int* x, int* y) {
	int tmp = *x;
	*x = *y;
	*y = tmp;
}
void AdJustDown(HPDataType* arr, int parent, int size) {
	int child = 2 * parent + 1;
	while (child < size) {
		if (child + 1 < size && arr[child] > arr[child + 1]) {
			child += 1;
		}
		if (arr[child] < arr[parent]) {
			swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else {
			break;
		}
	}
}
void AdJustUp(HPDataType* arr, int child) {
	int parent = (child - 1) / 2;
	while (child > 0) {
		if (arr[child] < arr[parent]) {
			swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else {
			break;
		}
	}
}
void HPPush(HP* php, HPDataType x) {
	assert(php);
	if (php->capacity == php->size) {
		int newCapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, sizeof(HPDataType) * newCapacity);
		if (tmp == NULL) {
			perror("malloc fail");
			exit(1);
		}
		php->arr = tmp;
		php->capacity = newCapacity;
	}
	php->arr[php->size] = x;
	AdJustUp(php->arr, php->size);
	php->size++;
}
void HPPop(HP* php) {
	assert(php && php->size);
	swap(&php->arr[0], &php->arr[php->size - 1]);
	php->size--;
	AdJustDown(php->arr, 0, php->size);
}
bool HPEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}

HPDataType HPTop(HP* php)
{
	assert(php && php->size);

	return php->arr[0];
}